package tree;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;

import javax.swing.JOptionPane;

import sgf.SGFController;
import ui.GobanPanel;
import ui.Main;
import ui.TextEditorPane;
import util.Util;
import board.Board;

/**
 * Strategy for displaying interactive problems.
 * @author TKington
 *
 */
public class SGFDisplayStrategy implements IDisplayStrategy {
	/** Version for serialization. */
	private static final long serialVersionUID = 4435118897790834181L;

	/** The problem on this page in SGF format. */
	private String sgf;
	
	/**
	 * Creates a new SGFDisplayStrategy object.
	 * @param sgf the problem, in SGF format
	 */
	public SGFDisplayStrategy(String sgf) {
		this.sgf = sgf;
	}

	public void display(PageNode curPage, GobanPanel goban, Board board) {
		//	This should be first, so the validate event is queued before
		//	repaints caused later - this avoids jumping when 
		//	widgetPanel appears/disappears.
		Main.frame.showWidgetPanel();
		Main.frame.enableActions(false, true);

		SGFController sgfController = SGFController.instance();
    	goban.setGobanListener(sgfController);
    	sgfController.setBoard(board);
    	
    	TextEditorPane.instance().setMode(TextEditorPane.TEXTMODE_VIEWHTML);
    	
    	sgfController.startProblem(sgf);
	}
	
	public void setTextPaneMode(int mode) {
		//	NOTE: This will be called when TextEditorPane.setMode
		//		  is called above.
	}
	
	public void leavingPage() { /* */ }
	
	@Override
	public SGFDisplayStrategy clone() {
		return new SGFDisplayStrategy(sgf);
	}
	
	@Override
	public boolean equals(Object o) {
		if(!(o instanceof SGFDisplayStrategy))
			return false;
		
		SGFDisplayStrategy s = (SGFDisplayStrategy)o;
		return sgf.equals(s.sgf);
	}
	
	/**
	 * Exports the SGF to a file.
	 * @param file the file
	 * @return true if successful
	 */
	public boolean exportSGF(File file) {
		PrintWriter out;
		try {
			out = new PrintWriter(new FileWriter(file));
			out.println(sgf);
			out.close();
			return true;
		} catch (IOException e) {
			JOptionPane.showMessageDialog(Main.frame, "Error exporting SGF. See viewer.log for details.");
			Util.logSilent(e);
			return false;
		}
	}
}
